/**
 * 用 C 语言实现栈基本操作（入栈、出栈、查看栈顶元素、判断栈是否为空）的程序：
 */
#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
#define OVERFLOW 0
#define ElemType int
#define Status int
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct SqStack{
    ElemType *base;
    ElemType *top;
    int stacksize;

}SqStack;
//初始化
Status InitStack(SqStack* S){
    S->base =(ElemType*)malloc(STACK_INIT_SIZE *sizeof(ElemType));
    if(S->base==NULL){
        return ERROR;
    }
    S->top=S->base;
    S->stacksize = STACK_INIT_SIZE;//栈的大小
    return OK;
}
//入栈
Status Push(SqStack* S,ElemType e){
    //站存在
    if(S==NULL)return ERROR;
    //判断满
    if(S->top-S->base >=S->stacksize){
        S->base=(ElemType*)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(ElemType));
         //是否申请空间成功
        if(S->base==NULL){
        exit(OVERFLOW) ;
        }
       //找到栈顶
        S->top=S->base +S->stacksize;
        //更新
        S->stacksize=S->stacksize+STACKINCREMENT;
    }
    //存元素，base也存
    *(S->top)=e;
    S->top++;
    return OK;
}
//出栈
Status Pop(SqStack* S,ElemType* e){
    //空？
    if(S->base==S->top){
        return ERROR;
    }
    //出栈
    *e=*(--S->top);
    S->stacksize=S->top-S->base;
    return OK;
}
//获取栈顶元素
Status GetTop(SqStack* S,ElemType* e){
     //空？
    if(S->base==S->top){
        return ERROR;
    }
    *e=*(S->top-1);
    return OK;
}
//判断栈是否为空
Status IsEmpty(SqStack* S){
    if(S->base==S->top){
        return OK;
    }
    return ERROR;
}
int main(){
    SqStack S;
    InitStack(&S);
    Push(&S,1);
    Push(&S,2);
    Push(&S,3);
    Push(&S,4);
    Push(&S,5);
    Push(&S,6);
    int E=0;
    GetTop(&S,&E);
    printf("%d\n",E);
    Pop(&S,&E);
    printf("%d\n",E);
    free(S.base);
}

